import time
from datetime import timedelta, datetime
from flask import render_template, request, redirect, url_for, session, g, current_app, jsonify, abort

from info import db
from info.constants import ADMIN_USER_PAGE_MAX_COUNT, ADMIN_NEWS_PAGE_MAX_COUNT, QINIU_DOMIN_PREFIX
from info.models import User, News, Category
from info.modules.admin import admin_blue
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET


@admin_blue.route("/login",methods=["post","get"])
def login():
    if request.method=="GET":
        user_id=session.get("user_id",None)
        is_admin=session.get("is_admin",False)
        if user_id and is_admin:
            return redirect(url_for("admin.index"))
        return render_template("admin/login.html")
    username=request.form.get("username")
    password=request.form.get("password")
    if not all([username,password]):
        return render_template("admin/login.html",data={"errmsg":"参数不全"})
    try:
        user=User.query.filter(User.nick_name==username).first()
    except Exception as e:
        return render_template("admin/login.html", data={"errmsg": "数据库查询错误"})
    if not user:
        return render_template("admin/login.html", data={"errmsg": "用户名不存在"})
    if not user.check_passowrd(password):
        return render_template("admin/login.html", data={"errmsg": "密码错误"})
    session["nick_name"]=user.nick_name
    session["mobile"]=user.mobile
    session["user_id"]=user.id
    session["is_admin"]=True
    return redirect(url_for("admin.index"))


@admin_blue.route("/index")
@user_login_data
def index():
    user=g.user
    data={"user":user}
    return render_template("admin/index.html",data=data)

@admin_blue.route("/user_count")
def user_count():
    total_count=0
    try:
        total_count=User.query.filter(User.is_admin==False).count()
    except Exception as e:
        current_app.logger.error(e)
    now=time.localtime()
    month_day="%d-%02d-01"%(now.tm_year,now.tm_mon)
    month_time= datetime.strptime(month_day, "%Y-%m-%d")
    month_count=0
    try:
        month_count=User.query.filter(User.is_admin==False,User.last_login>month_time).count()
    except Exception as e:
        current_app.logger.error(e)
    day="%d-%02d-%d"%(now.tm_year,now.tm_mon,now.tm_mday)
    day_time =datetime.strptime(day, "%Y-%m-%d")
    day_count=0
    try:
        day_count=User.query.filter(User.is_admin==False,User.last_login>day_time).count()
    except Exception as e:
        current_app.logger.error(e)
    date_list=[]
    t= datetime.strptime(datetime.now().strftime("%Y-%m-%d"), "%Y-%m-%d")
    count=0
    user_list=[]
    time_list=[]
    for i in range(0,31):
        begin_time= t-timedelta(days=i)
        end_time=t+timedelta(days=1-i)
        count=User.query.filter(User.is_admin==False,User.last_login>begin_time,User.last_login<end_time).count()
        user_list.append(count)
        time_list.append(begin_time.strftime("%Y-%m-%d"))
    user_list.reverse()
    time_list.reverse()
    data={
        "total_count":total_count,
        "month_count":month_count,
        "day_count":day_count,
        "user_list":user_list,
        "time_list":time_list
    }
    return render_template("admin/user_count.html",data=data)


@admin_blue.route("/user_list")
def user_list():
    p=request.args.get("p","1")
    paginate=None
    p=int(p)
    try:
        paginate=User.query.paginate(p,ADMIN_USER_PAGE_MAX_COUNT,False)
    except Exception as e:
        current_app.logger.error(e)
    user_list=paginate.items
    page=paginate.page
    pages=paginate.pages
    new_user_list=[]
    for user in user_list:
        new_user_list.append(user.to_admin_dict())
    data={
        "users":new_user_list,
        "page":page,
        "pages":pages
    }
    return render_template("admin/user_list.html",data=data)

@admin_blue.route("/user_review")
def user_review():
    p=request.args.get("p","1")
    keywords=request.args.get("keywords")
    p=int(p)
    paginate=None
    filters=[News.status!=0]
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate=News.query.filter(*filters).order_by(News.create_time.desc()).paginate(p,ADMIN_NEWS_PAGE_MAX_COUNT,False)
    except Exception as e:
        current_app.logger.error(e)
    news_list=paginate.items
    page=paginate.page
    pages=paginate.pages
    new_news_list=[]
    for news in news_list:
        new_news_list.append(news.to_review_dict())
    data={
        "news_list":new_news_list,
        "page":page,
        "pages":pages
    }
    return render_template("admin/news_review.html",data=data)


@admin_blue.route("/news_review_detail",methods=["post","get"])
def news_review_detail():
    if request.method=="GET":
        news_id=request.args.get("news_id",None)
        news_id=int(news_id)
        if not news_id:
            return render_template("admin/news_review_detail.html",data={"errmsg":"没有参数"})
        news=None
        try:
            news=News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
        if not news:
            return render_template("admin/news_review_detail.html",data={"errmsg":"没有查询到这个新闻"})
        data={"news":news}
        return render_template("admin/news_review_detail.html",data=data)
    news_id=request.json.get("news_id",None)
    action=request.json.get("action",None)

    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    if action not in (["accept","reject"]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    try:
        news=News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库查询错误")
    if not news:
        return jsonify(errno=RET.NODATA,errmsg="没有这条新闻")
    if action=="accept":
        news.status=0
    else:
        reason = request.json.get("reason", None)
        if not reason:
            return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
        news.status=-1
        news.reason=reason
    return jsonify(errno=RET.OK,errmsg="OK")


@admin_blue.route("/news_edit")
def news_edit():
    p=request.args.get("p","1")
    keywords=request.args.get("keywords",None)
    p=int(p)
    filters=[News.status==0]
    paginate=None
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate=News.query.filter(*filters).order_by(News.create_time.desc()).paginate(p,ADMIN_NEWS_PAGE_MAX_COUNT,False)
    except Exception as e:
        current_app.logger.error(e)
    news_list=paginate.items
    page=paginate.page
    pages=paginate.pages
    new_news_list=[]
    for news in news_list:
        new_news_list.append(news.to_basic_dict())
    data={
        "page":page,
        "pages":pages,
        "news_list":new_news_list
    }
    return render_template("admin/news_edit.html",data=data)


@admin_blue.route("/news_edit_detail",methods=["post","get"])
def news_edit_detail():
    if request.method=="GET":
        news_id=request.args.get("news_id",None)
        news=None
        try:
            news_id=int(news_id)
        except Exception as e:
            current_app.logger.error(e)
        try:
            news=News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
        if not news:
            abort(404)
        categories=[]
        try:
            categories=Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
        categories.pop(0)
        new_categories=[]
        for category in categories:
            category_dict=category.to_dict()
            if category.id==news.category_id:
                category_dict["is_selected"]=True
            else:
                category_dict["is_selected"] = False
            new_categories.append(category_dict)
        data={
            "news":news.to_dict(),
            "categories":new_categories
        }
        return render_template("admin/news_edit_detail.html",data=data)
    title=request.form.get("title")
    category_id=request.form.get("category_id")
    digest=request.form.get("digest")
    index_image=request.files.get("index_image")
    content=request.form.get("content")
    news_id=request.form.get("news_id")
    if not all([title,news_id,category_id,digest,content]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    news=None
    try:
        news=News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库查询错误")
    if not news:
        return jsonify(errno=RET.NODATA,errmsg="没有这条新闻")
    if index_image:
        try:
            url=storage(index_image.read())
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR,errmsg="第三方错误")
        news.index_image_url=QINIU_DOMIN_PREFIX+url

    news.title=title
    news.category_id=category_id
    news.digest=digest
    news.content=content
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库存储错误")
    return jsonify(errno=RET.OK,errmsg="OK")

@admin_blue.route("/news_category")
def get_news_category():
    categories=[]
    try:
        categories=Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    categories.pop(0)
    data={"categories":categories}
    return render_template("admin/news_type.html",data=data)

@admin_blue.route("/add_category",methods=["post"])
def add_category():
    id=request.json.get("id",None)
    name=request.json.get("name",None)
    if not name:
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    if id:
        category=Category.query.get(id)
        category.name=name
    else:
        category=Category()
        category.name=name
        db.session.add(category)
    return jsonify(errno=RET.OK,errmsg="OK")

